import {} from '../../utils/api.js'

import {
  getReqData
} from '../../utils/util.js'

//获取应用实例
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    theme: "light",
    items: [{
        name: '1',
        value: '男',
        checked: 'true'
      },
      {
        name: '2',
        value: '女'
      },
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function(options) {
    let {
      userInfo,
    } = app.globalData

    // 设置性别
    let {
      items
    } = this.data

    items.forEach(item => {
      if (item.name === userInfo.sex) item.checked = 'true'
    })

    userInfo.items = items

    // console.log('center_edit ', userInfo)

    this.setData({
      userInfo
    })
  },
  formSubmit: async function(e) {
    const {
      _id
    } = app.globalData.userInfo

    const {
      address,
      nickname,
      sex,
      telephone
    } = e.detail.value

    let {
      authing,
      userInfo
    } = app.globalData

    let requestList = []

    if (sex) {
      requestList.push(await authing.setMetadata({
        _id,
        key: "sex",
        value: sex
      }))
    }
    if (address) {
      requestList.push(
        await authing.setMetadata({
          _id,
          key: "address",
          value: address
        })
      )
    }
    if (telephone) {
      requestList.push(
        await authing.setMetadata({
          _id,
          key: "telephone",
          value: telephone
        })
      )
    }

    const results = await Promise.all(requestList)

    console.log('results ', results)

    results.forEach(item => {
      const {
        key,
        value
      } = item

      userInfo[key] = value
    })

    if (results.length > 0) {
      app.globalData.userInfo = userInfo
    }

    wx.showToast({
      title: results.length > 0 ? '成功保存' : '保存失败',
      duration: 1000
    })
  }
})